package com.ksyzt.ksite2.server.servlet;

import java.io.File;
import java.sql.SQLException;

import javax.servlet.jsp.jstl.sql.Result;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.ksyzt.gwt.server.common.Util;
import com.ksyzt.gwt.server.common.Utility;
import com.ksyzt.gwt.shared.module.SiteInformation;
import com.ksyzt.ksite2.client.service.ISysManager;
import com.ksyzt.ksite2.server.common.Application;
import com.ksyzt.ksite2.server.common.Logger;
import com.ksyzt.ksite2.server.database.base.AccessBase;
import com.ksyzt.ksite2.server.database.dao.IATTACHMENTDAO;
import com.ksyzt.ksite2.server.database.dao.ICOLUMNDAO;
import com.ksyzt.ksite2.server.database.dao.ILOGDAO;
import com.ksyzt.ksite2.server.database.dao.INEWSDAO;
import com.ksyzt.ksite2.server.database.dao.IORGANIZATIONDAO;
import com.ksyzt.ksite2.server.database.dao.IPUSERDAO;
import com.ksyzt.ksite2.server.database.dao.ISITEINFODAO;
import com.ksyzt.ksite2.server.database.dao.IVW_NEWSDAO;
import com.ksyzt.ksite2.server.database.dao.impl.ATTACHMENTDAOImpl;
import com.ksyzt.ksite2.server.database.dao.impl.COLUMNDAOImpl;
import com.ksyzt.ksite2.server.database.dao.impl.LOGDAOImpl;
import com.ksyzt.ksite2.server.database.dao.impl.NEWSDAOImpl;
import com.ksyzt.ksite2.server.database.dao.impl.ORGANIZATIONDAOImpl;
import com.ksyzt.ksite2.server.database.dao.impl.PUSERDAOImpl;
import com.ksyzt.ksite2.server.database.dao.impl.SITEINFODAOImpl;
import com.ksyzt.ksite2.server.database.dao.impl.VW_NEWSDAOImpl;
import com.ksyzt.ksite2.shared.OrgType;
import com.ksyzt.ksite2.shared.PageData;
import com.ksyzt.ksite2.shared.PageLoggerData;
import com.ksyzt.ksite2.shared.PageNewsData;
import com.ksyzt.ksite2.shared.SysConst;
import com.ksyzt.ksite2.shared.modle.ATTACHMENTObj;
import com.ksyzt.ksite2.shared.modle.ATTACHMENTObjs;
import com.ksyzt.ksite2.shared.modle.COLUMNObj;
import com.ksyzt.ksite2.shared.modle.COLUMNObjs;
import com.ksyzt.ksite2.shared.modle.NEWSObj;
import com.ksyzt.ksite2.shared.modle.ORGANIZATIONObj;
import com.ksyzt.ksite2.shared.modle.ORGANIZATIONObjs;
import com.ksyzt.ksite2.shared.modle.PUSERObj;
import com.ksyzt.ksite2.shared.modle.PUSERObjs;
import com.ksyzt.ksite2.shared.modle.SITEINFOObj;
import com.ksyzt.ksite2.shared.modle.VW_NEWSObj;

public class SystemConsole extends RemoteServiceServlet implements ISysManager {

	private static final long serialVersionUID = 1L;

	@Override
	public PUSERObj login(String name, String pwd) throws Exception {
		if (name == null || name.equals("")) {
			throw new Exception(SysConst.MSG_REQUIRE_NAME);
		}
		IPUSERDAO dao = new PUSERDAOImpl(Application.getConnection());
		PUSERObjs ops = dao.selectByWhereTemplate("where name=?", name);

		if (ops.size() == 0) {
			throw new Exception(SysConst.MSG_NO_USER);
		} else {
			pwd = Utility.encrypt(pwd);
			PUSERObj user = ops.get(0);
			if (user.getPWD() == null || !user.getPWD().equals(pwd)) {
				Logger.Loger(Logger.LEVEL_INFO, name, "尝试登录失败");
				throw new Exception(SysConst.MSG_WRONG_PWD);
			} else {
				user.setLOGINCOUNT(user.getLOGINCOUNT() + 1);
				user.setLASTTIME(Util.getCurrentSQLTimestamp());
				dao.updateObjectByPK(user);
				Application app = new Application(this.getThreadLocalRequest(),
						this.getThreadLocalResponse());
				app.setCurrentUser(user);

				Logger.Loger(Logger.LEVEL_INFO, name, "尝试登录成功");
				return user;
			}
		}
	}

	@Override
	public PUSERObj checkCurrentUser() throws Exception {
		Application app = new Application(this.getThreadLocalRequest(),
				this.getThreadLocalResponse());
		return app.getCurrentUser();
	}

	@Override
	public void quit_sys_console() throws Exception {
		Application app = new Application(this.getThreadLocalRequest(),
				this.getThreadLocalResponse());
		PUSERObj u = app.getCurrentUser();
		if (u != null) {

			Logger.Loger(Logger.LEVEL_INFO, u.getNAME(), "退出系统");
		}
		app.setCurrentUser(null);

	}

	public Boolean deleteOrganization(int oid) throws Exception {
		IORGANIZATIONDAO dao = new ORGANIZATIONDAOImpl(
				Application.getConnection());
		ORGANIZATIONObj org = dao.selectByPK(oid);
		Integer count = org.getCHILDREN();
		if (count > 0) {
			throw new Exception("节点有子节点，不能删除");
		} else if (org.getSYS() > 0) {
			throw new Exception("系统保留配置，不能删除");
		} else {

			long tempcount = 0;
			String str = "";

			switch (org.getOTYPE()) {
			case OrgType.OT_BBS: {
				// 论坛分类 判断是否有 论坛的分组信息

				break;
			}
			case OrgType.OT_NEWS: {
				// 新闻分类 判断是否有 新闻的分组信息
				INEWSDAO daogroup = new NEWSDAOImpl(Application.getConnection());
				tempcount = daogroup.getCountByWhereTemplate("where oid=?",
						org.getID());
				str = "新闻分组信息:" + tempcount;
				break;
			}
			case OrgType.OT_PRODUCT_CATALOG: {

				break;
			}
			case OrgType.OT_SCHOOL: {
				// todo: 将来添加
				break;
			}
			}

			if (tempcount == 0) {
				dao.deleteByWhereTemplate("where oid=?", oid);
			} else {
				throw new Exception("该节点有内容:" + str + "，不能删除");
			}
		}
		return true;
	}

	public ORGANIZATIONObjs getOrganizationChildren(int pid) throws Exception {
		ORGANIZATIONObjs r = null;
		IORGANIZATIONDAO dao = new ORGANIZATIONDAOImpl(
				Application.getConnection());
		r = dao.selectByWhereTemplate("where  pid=? order by rankval asc", pid);
		return r;
	}

	public ORGANIZATIONObjs getOrganizations(int userid, int orgtype)
			throws Exception {
		ORGANIZATIONObjs r = null;
		IORGANIZATIONDAO dao = new ORGANIZATIONDAOImpl(
				Application.getConnection());
		r = dao.selectByWhereTemplate(
				"where whoid=? and otype=? and pid=-1 order by rankval asc",
				userid, orgtype);
		return r;
	}

	public ORGANIZATIONObj modifyOrganization(ORGANIZATIONObj org)
			throws Exception {

		IORGANIZATIONDAO dao = new ORGANIZATIONDAOImpl(
				Application.getConnection());
		if (org.getID() != null) {
			ORGANIZATIONObj old = dao.selectByPK(org.getID());
			dao.updateObjectByPK(org);

			if (org.getNAME() != null && !old.getNAME().equals(org.getNAME())) {
				// 更新路径信息
				String pathold = old.getNAME() + ";" + old.getID();
				String pathnew = org.getNAME() + ";" + org.getID();
				String sql = "";
				if (old.getPID() == -1) {
					sql = "update organization set path=replace(path,'"
							+ pathold + "','" + pathnew + "') where rootid="
							+ old.getID();
				} else {
					sql = "update organization set path=replace(path,'"
							+ pathold + "','" + pathnew + "') where rootid="
							+ old.getROOTID();
				}

				AccessBase a = new AccessBase(Application.getConnection());
				a.executeDDL(sql);
			}
		} else {
			ORGANIZATIONObj o = dao.selectByPK(org.getPID());
			if (o != null) {
				// 子节点的路径
				String path = o.getPATH() + "/" + o.getNAME() + ";" + o.getID();
				org.setPATH(path);
			} else {
				org.setPATH("");
			}
			org.setCDATE(Util.getCurrentSQLTimestamp());
			org.setCHILDREN(0);
			dao.insertObject(org);

			if (o != null) {
				Long count = dao.getCountByWhereTemplate("where pid=?",
						org.getPID());
				o.setCHILDREN(count.intValue());
				dao.updateObjectByPK(o);
			}
		}
		return org;
	}

	public ORGANIZATIONObjs getAllChildrens(int rootid) throws Exception {

		ORGANIZATIONObjs r = null;
		IORGANIZATIONDAO dao = new ORGANIZATIONDAOImpl(
				Application.getConnection());
		try {
			r = dao.selectByWhereTemplate(
					"where rootid=? order by pid asc,rankval asc", rootid);
			// System.out.println("children:>" + r);
		} catch (SQLException e) {
			throw new Exception(e.getMessage());
		}
		return r;
	}

	// /////////////////////////////////////////////////// column implements

	public COLUMNObjs getColumns(int userid, int orgtype) throws Exception {
		COLUMNObjs r = null;
		ICOLUMNDAO dao = new COLUMNDAOImpl(Application.getConnection());
		r = dao.selectByWhereTemplate(
				"where whoid=? and otype=? and pid=-1 order by rankval asc",
				userid, orgtype);
		return r;
	}

	public COLUMNObjs getColumnChildren(int pid) throws Exception {
		COLUMNObjs r = null;
		ICOLUMNDAO dao = new COLUMNDAOImpl(Application.getConnection());
		r = dao.selectByWhereTemplate("where  pid=? order by rankval asc", pid);
		return r;
	}

	public COLUMNObj modifyColumn(COLUMNObj org) throws Exception {
		ICOLUMNDAO dao = new COLUMNDAOImpl(Application.getConnection());
		if (org.getID() != null) {
			COLUMNObj old = dao.selectByPK(org.getID());
			dao.updateObjectByPK(org);

			if (org.getNAME() != null && !old.getNAME().equals(org.getNAME())) {
				// 更新路径信息
				String pathold = old.getNAME() + ";" + old.getID();
				String pathnew = org.getNAME() + ";" + org.getID();
				String sql = "";
				if (old.getPID() == -1) {
					sql = "update `COLUMN` set path=replace(path,'" + pathold
							+ "','" + pathnew
							+ "') ,textpath=replace(textpath,'" + pathold
							+ "','" + pathnew + "') where rootid="
							+ old.getID();
				} else {
					sql = "update `COLUMN` set path=replace(path,'" + pathold
							+ "','" + pathnew
							+ "') ,textpath=replace(textpath,'" + pathold
							+ "','" + pathnew + "') where rootid="
							+ old.getROOTID();
				}

				AccessBase a = new AccessBase(Application.getConnection());
				a.executeDDL(sql);

			}
		} else {
			COLUMNObj o = dao.selectByPK(org.getPID());
			if (o != null) {
				// 子节点的路径
				String path;

				if (o.getPATH() == null || o.getPATH().equals("")) {
					path = o.getNAME() + ";" + o.getID();
				} else {
					path = o.getPATH() + "/" + o.getNAME() + ";" + o.getID();
				}
				org.setPATH(path);
				String textPath;

				if (o.getTEXTPATH() == null || o.getTEXTPATH().equals("")) {
					textPath = o.getNAME();
				} else {
					textPath = o.getTEXTPATH() + ">" + o.getNAME();
				}
				org.setTEXTPATH(textPath);
			} else {
				org.setPATH("");
				org.setTEXTPATH("");
			}
			org.setCDATE(Util.getCurrentSQLTimestamp());
			org.setCHILDREN(0);

			// 获取Rankval的最小值
			int rankval = 0;
			String sql = "select min(rankval) from `column` where pid="
					+ org.getPID();
			Result r = dao.execute(sql);
			if (r.getRowCount() > 0) {
				Integer d = (Integer) r.getRowsByIndex()[0][0];
				if (d != null) {
					rankval = d.intValue() - 1;
				}
			}
			org.setRANKVAL(rankval);
			dao.insertObject(org);

			if (o != null) {
				Long count = dao.getCountByWhereTemplate("where pid=?",
						org.getPID());
				o.setCHILDREN(count.intValue());
				dao.updateObjectByPK(o);
			}
		}
		return org;
	}

	public Boolean deleteColumn(int id) throws Exception {
		ICOLUMNDAO dao = new COLUMNDAOImpl(Application.getConnection());
		COLUMNObj org = dao.selectByPK(id);
		Integer count = org.getCHILDREN();
		if (count > 0) {
			throw new Exception("节点有子节点，不能删除");
		} else if (org.getSYS() > 0) {
			throw new Exception("系统保留配置，不能删除");
		} else {

			long tempcount = 0;
			String str = "";

			// switch (org.getOTYPE()) {

			// case OrgType.OT_NEWS: {
			// 新闻分类 判断是否有 新闻的分组信息
			INEWSDAO daogroup = new NEWSDAOImpl(Application.getConnection());
			tempcount = daogroup.getCountByWhereTemplate("where oid=?",
					org.getID());
			str = "新闻分组信息:" + tempcount;
			// break;
			// }
			// }

			if (tempcount == 0) {
				dao.deleteByWhereTemplate("where id=?", id);
			} else {
				throw new Exception("该节点有内容:" + str + "，不能删除");
			}
		}
		return true;
	}

	public COLUMNObjs getAllColumnChildrens(int rootid) throws Exception {
		COLUMNObjs r = null;
		ICOLUMNDAO dao = new COLUMNDAOImpl(Application.getConnection());
		try {
			r = dao.selectByWhereTemplate(
					"where rootid=? order by pid asc,rankval asc", rootid);
		} catch (SQLException e) {
			e.printStackTrace();
			// System.out.println("column children error:" + e.getMessage());
			throw new Exception("SQL ERROR" + e.getMessage());
		}
		// System.out.println("column children:" + r.size());
		return r;
	}

	public static void main(String[] args) {
		SystemConsole app = new SystemConsole();
		try {
			COLUMNObjs cs = app.getAllColumnChildrens(25);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**************************** news mamaner ********************************/
	public Application getApp() {
		Application app = new Application(this.getThreadLocalRequest(),
				this.getThreadLocalResponse());
		return app;
	}

	public void updateSiteInfo(SITEINFOObj siteinfo) throws Exception {
		ISITEINFODAO dao = new SITEINFODAOImpl(Application.getConnection());
		dao.updateObjectByPK(siteinfo);
		clearSiteInfo();
		return;
	}

	/**
	 * 更新系统模板
	 */
	public String updateTemplate() {

		String ok = "更新完毕";
		Application app = this.getApp();
		String base = app.getRealPath("/");

		return ok;
	}

	public void deleteNews(int nid) throws Exception {
		Application app = getApp();
		PUSERObj user = app.getCurrentUser();

		if (user == null) {
			throw new Exception("需要登录");
		} else {
			INEWSDAO dao = new NEWSDAOImpl(Application.getConnection());
			NEWSObj n = dao.selectByPK(nid);
			if (n == null) {
				throw new Exception("没有此新闻");
			}

			if (!user.getID().equals(n.getUSERID())) {
				throw new Exception("此新闻不是您创建的！");
			}
			try {
				dao.deleteByPK(nid);
				Logger.Loger(Logger.LEVEL_INFO, user.getNAME(),
						"删除新闻" + n.getTITLE());
			} catch (SQLException e) {
				throw new Exception(e.getMessage());
			}
		}
	}

	public PageNewsData getNews(int oid, int page, int pagesize)
			throws Exception {
		PageNewsData data = new PageNewsData();
		data.currentPage = page;
		data.pagesize = pagesize;

		try {
			INEWSDAO dao = new NEWSDAOImpl(Application.getConnection());
			data.total = (int) dao.getCountByWhereTemplate("where oid=?", oid);

			IVW_NEWSDAO dao1 = new VW_NEWSDAOImpl(Application.getConnection());
			data.news = dao1.getSpecificRecordByWhereTemplate(
					"where oid=? order by addtime desc", page * pagesize, page
							* pagesize + pagesize, oid);
		} catch (SQLException e) {
			throw new Exception(e.getMessage());
		}
		return data;
	}

	public PageNewsData searchNews(String tag, int page, int pagesize)
			throws Exception {
		PageNewsData data = new PageNewsData();
		data.currentPage = page;
		data.pagesize = pagesize;

		try {

			IVW_NEWSDAO dao1 = new VW_NEWSDAOImpl(Application.getConnection());
			data.total = (int) dao1.getCountByWhereTemplate("where tag like ?",
					tag);
			data.news = dao1.getSpecificRecordByWhereTemplate(
					"where tag like ?", page * pagesize, page * pagesize
							+ pagesize, tag);
		} catch (SQLException e) {
			throw new Exception(e.getMessage());
		}
		return data;
	}

	public VW_NEWSObj submitNews(NEWSObj news) throws Exception {
		Application app = getApp();
		PUSERObj user = app.getCurrentUser();

		if (user == null) {
			throw new Exception("需要登录");
		} else {
			INEWSDAO dao = new NEWSDAOImpl(Application.getConnection());

			try {
				if (news.getID() == null) {
					if (news.getADDTIME() == null) {
						news.setADDTIME(Util.getCurrentSQLTimestamp());
					}
					news.setUSERID(user.getID());
					news.setUPDATETIME(news.getADDTIME());
					dao.insertObject(news);

					Logger.Loger(Logger.LEVEL_INFO, user.getNAME(), "添加新闻"
							+ news.getTITLE());
				} else {

					dao.updateObjectByPK(news);

					Logger.Loger(Logger.LEVEL_INFO, user.getNAME(), "更新新闻"
							+ news.getTITLE());
				}
				IVW_NEWSDAO dao1 = new VW_NEWSDAOImpl(
						Application.getConnection());
				VW_NEWSObj news1 = dao1.findByID(news.getID());
				return news1;
			} catch (SQLException e) {
				throw new Exception(e.getMessage());
			}
		}
	}

	public void changeNewsOid(String sb, Integer oid) throws Exception {
		Application app = getApp();
		PUSERObj user = app.getCurrentUser();

		if (user == null) {
			throw new Exception("需要登录");
		} else {

			INEWSDAO dao = new NEWSDAOImpl(Application.getConnection());
			String[] ids = sb.split(",");

			for (int i = 0; i < ids.length; i++) {
				String id = ids[i];
				if (!id.equals("")) {
					Integer nid = Integer.valueOf(id);
					NEWSObj n = new NEWSObj();
					n.setID(nid);
					n.setOID(oid);
					try {
						dao.updateObjectByPK(n);
					} catch (SQLException e) {
						throw new Exception(e.getMessage());
					}
				}
			}

		}
	}

	/**
	 * 清空组织的缓存数据
	 * 
	 * @param oid
	 */
	public void clearOrganizationCache(Integer oid) throws Exception {
		Application app = getApp();
		String path = app.getRealPath("/data");
		String file = path + "/org" + oid + ".xml";
		File f = new File(file);
		if (f.exists()) {
			f.delete();
		}
	}

	public void clearSiteInfo() throws Exception {

		return;
	}

	public SiteInformation getSiteInfo() throws Exception {

		Application app = getApp();
		PageData gdata = app.getApplicationPageData();
		return gdata.siteInfo;
	}

	@Override
	public ATTACHMENTObjs getAttatchments(String nid) throws Exception {
		IATTACHMENTDAO dao = new ATTACHMENTDAOImpl(Application.getConnection());
		ATTACHMENTObjs atts = null;
		atts = dao.selectByWhereTemplate("where nid=? order by cdate asc", nid);
		return atts;
	}

	@Override
	public void deleteAttatchment(Integer aid) throws Exception {
		IATTACHMENTDAO dao = new ATTACHMENTDAOImpl(Application.getConnection());

		ATTACHMENTObj att = dao.selectByPK(aid);

		if (att != null) {

			String rootpath = getThreadLocalRequest().getRealPath("/");
			File f = new File(rootpath + att.getFILEPATH());
			if (f.exists()) {
				f.delete();
			}
			try {
				dao.deleteByPK(att.getAID());
			} catch (SQLException e) {
				e.printStackTrace();
				throw new Exception("不能删除数据库信息");
			}
		}

	}

	@Override
	public void updateAttatchment(ATTACHMENTObj att) throws Exception {
		IATTACHMENTDAO dao = new ATTACHMENTDAOImpl(Application.getConnection());
		if (att != null && att.getAID() != null) {
			dao.updateObjectByPK(att);
		}

	}

	@Override
	public COLUMNObj getColumn(int columnid) throws Exception {
		ICOLUMNDAO dao = new COLUMNDAOImpl(Application.getConnection());
		try {
			return dao.findByID(columnid);
		} catch (SQLException e) {
			throw new Exception("没有栏目信息");
		}
	}

	/*************************************** Logger *********************************/
	@Override
	public PageLoggerData getLogger(int page, int pagesize) throws Exception {
		PageLoggerData data = new PageLoggerData();
		data.currentPage = page;
		data.pagesize = pagesize;

		try {
			ILOGDAO dao = new LOGDAOImpl(Application.getConnection());
			data.total = (int) dao.getCountByWhereTemplate("");

			data.logs = dao.getSpecificRecordByWhereTemplate(
					"order by addtime desc", page * pagesize, page * pagesize
							+ pagesize);
		} catch (SQLException e) {
			throw new Exception(e.getMessage());
		}
		return data;
	}

}
